<template>
  <el-upload
    action=""
    :show-upload-list="false"
    :before-upload="onUpload"
    style="display: inline-block; vertical-align: bottom; margin-top: 10px"
  >
    <el-button
      class="ele-btn-icon"
      :icon="Upload"
      :type="bottonType"
      :size="bottonSize"
    >
      {{ bottonText }}
    </el-button>
  </el-upload>
</template>

<script setup>
  import { Upload } from '@element-plus/icons-vue';
  import { EleMessage } from 'ele-admin-plus/es';
  import { ref, onMounted } from 'vue';
  import axios from 'axios';
  import { fetchQiniuToken } from '@/utils/qiniu';
  const props = defineProps({
    /** 绑定值 */
    modelValue: String,
    /** 选择数量限制 */
    limit: {
      type: Number,
      default: 20
    },
    bottonText: {
      type: String,
      default: '上传'
    },
    bottonType: {
      type: String,
      default: 'primary'
    },
    bottonSize: {
      type: String,
      default: 'default'
    },
    /** 文件大小限制, 单位MB */
    fileLimit: {
      type: Number,
      default: 1
    },
    bottonText: {
      type: String,
      default: '上传'
    },

    /** 自定义样式 */
    itemStyle: Object,
    /** 自定义上传按钮样式 */
    buttonStyle: Object,
    /** 接受上传的文件类型 */
    accept: {
      type: String,
      default: ''
    }
  });
  const emit = defineEmits(['done']);

  /** 上传 */
  const onUpload = (file) => {
    if (file.size / 1024 / 1024 > 100) {
      EleMessage.error('大小不能超过 100MB');
      return false;
    }
    const loading = EleMessage.loading('上传中..');
    uploadQiniu(file)
      .then((res) => {
        console.log(res, '上传完成，七牛返回的参数');
        let url = imagesUrl.value + res.key;
        console.log(url, '地址');
        emit('done', url);
        loading.close();
      })
      .catch((e) => {
        EleMessage.error(e.message);
        loading.close();
      });
    return false;
  };
  // 七牛
  const uploadUrl = ref('');
  const imagesUrl = ref('');
  /** 上传七牛用到的参数 */
  const postData = ref({
    token: '',
    key: '',
    file: {}
  });
  onMounted(async () => {
    let qiniu = await fetchQiniuToken(); // 只会发一次请求
    postData.value.token = qiniu.token;
    uploadUrl.value = qiniu.uploadUrl;
    imagesUrl.value = qiniu.imagesUrl;
  });
  const uploadQiniu = async (request) => {
    const promise = new Promise((resolve, reject) => {
      const config = {
        headers: { 'Content-Type': 'multipart/form-data' }
      };
      const filePath = request.name;
      // 获取最后一个.的位置
      var index = filePath.lastIndexOf('.');
      // 获取后缀
      var ext = filePath.substr(index + 1);
      // 输出结果
      const key = `${new Date().getTime()}${Math.floor(
        Math.random() * 100
      )}.${ext}`; // 自定义文件名
      console.log(request);
      const fd = new FormData();
      fd.append('file', request);
      fd.append('token', postData.value.token);
      fd.append('key', key);
      // console.log(this.axios)
      axios
        .post(uploadUrl.value, fd, config)
        .then((res) => {
          if (res.status === 200 && res.data) {
            resolve(res.data);
          } else {
            reject(res);
          }
        })
        .catch((err) => {
          console.log(err);
          EleMessage.error({
            message: `上传失败[${err.status}]`,
            duration: 2000
          });
        });
    });
    return promise;
  };
</script>

<style scoped lang="scss">
  .ele-attachment-upload.ele-upload-list {
    width: 100%;

    :deep(.ele-upload-item) {
      display: block;
      width: 100%;
      height: 26px;
      margin: 0 0 6px 0;
      padding: 0 20px 0 8px;
    }

    :deep(.ele-upload-button) {
      padding: 0;

      .ele-upload-icon {
        font-size: 15px;
      }
    }

    :deep(.ele-upload-progress) {
      flex-direction: row;
      align-items: center;
      justify-content: flex-start;
      padding: 0 20px 0 8px;

      .ele-upload-text {
        flex: 1;
        margin-bottom: 0;
      }

      .ele-upload-retry {
        margin: 0;
      }

      .el-progress {
        position: absolute;
        left: 4px;
        right: 4px;
        bottom: 0;
      }
    }

    .ele-upload-thumbnail {
      flex-direction: row;
      justify-content: flex-start;
    }

    .ele-attachment-text {
      flex: 1;
      font-size: 14px;
      line-height: 22px;
      text-align: left;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      word-break: break-all;
    }
  }
</style>
